import soundfile
import librosa
import matplotlib.pyplot as plt
import numpy as np


def main():
	filename = "../resources/C2_2_y.wav"
	data, sample_rate = soundfile.read(filename)
	print(data.shape)
	data = data*1.0/(max(abs(data)))#wave幅值归一化
	plt.specgram(data, Fs = sample_rate, scale_by_freq = True, sides = 'default')
	plt.ylabel('Frequency(Hz)')
	plt.xlabel('Time(s)')
	plt.show()


def main2():
	filename = "../resources/C2_2_y.wav"
	data, sample_rate = soundfile.read(filename)

	
	wave = np.array(data, dtype = "float")

	frame_off = 160
	frame_len = 400
	spect_len = 512

	frame_num = (wave.size - frame_len) // frame_off + 1
	# 生成汉明窗
	hamwindow = np.hamming(frame_len)
	spect = np.zeros((frame_num, spect_len // 2 + 1))
	z = np.zeros(spect_len - frame_len)

	for idx in range(frame_num):
	    base = idx * frame_off
	    frame = wave[base: base + frame_len]            # 分帧
	    frame = np.append(frame * hamwindow, z)         # 加窗
	    spect[idx:] = np.log10(np.abs(np.fft.rfft(frame))) # FFT，返回幅度谱

	plt.title("wavname")
	plt.imshow(np.transpose(spect), origin="lower", cmap = "jet", aspect = "auto", interpolation = "none")
	xlocs = np.linspace(0, frame_num - 1, 5)
	frame_dur = 1 / float(sample_rate) * frame_off
	plt.xticks(xlocs, ["%.02f" % l for l in (xlocs * frame_dur)])
	plt.xlabel("time (s)")
	plt.show()



if __name__ == '__main__':
	main2()